#include "kernel_operator.h"

constexpr int32_t TOTAL_LENGTH = 8 * 2048;                            // total length of data
constexpr int32_t USE_CORE_NUM = 8;                                   // num of core used
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;         // length computed of each core
constexpr int32_t TILE_NUM = 8;                                       // split data into 8 tiles for each core
constexpr int32_t BUFFER_NUM = 2;                                     // tensor num for each queue
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM; // separate to 2 parts, due to double buffer

class KernelBinaryCrossEntropyGrad {
public:
    __aicore__ inline KernelBinaryCrossEntropyGrad() {}
    __aicore__ inline void Init(GM_ADDR logits, GM_ADDR labels, GM_ADDR grad, GM_ADDR weight, GM_ADDR outgrad)
    {
        logitsGm.SetGlobalBuffer((__gm__ float *)logits + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        labelsGm.SetGlobalBuffer((__gm__ float *)labels + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        gradGm.SetGlobalBuffer((__gm__ float *)grad + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        weightGm.SetGlobalBuffer((__gm__ float *)weight + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        outgradGm.SetGlobalBuffer((__gm__ float *)outgrad + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        pipe.InitBuffer(inQueueLogits, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(inQueueLabels, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(inQueueGrad, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(inQueueWeight, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(outQueueOutGrad, BUFFER_NUM, TILE_LENGTH * sizeof(float));
       
    }

    __aicore__ inline void Process()
    {
        int32_t loopCount = TILE_NUM * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> logitsLocal = inQueueLogits.AllocTensor<float>();
        AscendC::LocalTensor<float> labelsLocal = inQueueLabels.AllocTensor<float>();
        AscendC::LocalTensor<float> gradLocal = inQueueGrad.AllocTensor<float>();
        AscendC::LocalTensor<float> weightLocal = inQueueWeight.AllocTensor<float>();
        AscendC::DataCopy(logitsLocal, logitsGm[progress * TILE_LENGTH], TILE_LENGTH);
        AscendC::DataCopy(labelsLocal, labelsGm[progress * TILE_LENGTH], TILE_LENGTH);
        AscendC::DataCopy(gradLocal, gradGm[progress * TILE_LENGTH], TILE_LENGTH);
        AscendC::DataCopy(weightLocal, weightGm[progress * TILE_LENGTH], TILE_LENGTH);
        inQueueLogits.EnQue(logitsLocal);
        inQueueLabels.EnQue(labelsLocal);
        inQueueGrad.EnQue(gradLocal);
        inQueueWeight.EnQue(weightLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> logitsLocal = inQueueLogits.DeQue<float>();
        AscendC::LocalTensor<float> labelsLocal = inQueueLabels.DeQue<float>();
        AscendC::LocalTensor<float> gradLocal = inQueueGrad.DeQue<float>();
        AscendC::LocalTensor<float> weightLocal = inQueueWeight.DeQue<float>();
        AscendC::LocalTensor<float> outgradLocal = outQueueOutGrad.AllocTensor<float>();
            
        AscendC::Sub(logitsLocal, logitsLocal, labelsLocal, TILE_LENGTH);
        AscendC::Mul(logitsLocal, logitsLocal, gradLocal, TILE_LENGTH);
        AscendC::Mul(outgradLocal, logitsLocal, weightLocal, TILE_LENGTH);

        outQueueOutGrad.EnQue<float>(outgradLocal);
        inQueueLogits.FreeTensor(logitsLocal);
        inQueueLabels.FreeTensor(labelsLocal);
        inQueueGrad.FreeTensor(gradLocal);
        inQueueWeight.FreeTensor(weightLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> outgradLocal = outQueueOutGrad.DeQue<float>();
        AscendC::DataCopy(outgradGm[progress * TILE_LENGTH], outgradLocal, TILE_LENGTH);
        outQueueOutGrad.FreeTensor(outgradLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueLogits;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueLabels;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueGrad;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueWeight;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueOutGrad;

    AscendC::GlobalTensor<float> logitsGm;
    AscendC::GlobalTensor<float> labelsGm;
    AscendC::GlobalTensor<float> gradGm;
    AscendC::GlobalTensor<float> weightGm;
    AscendC::GlobalTensor<float> outgradGm;
};

extern "C" __global__ __aicore__ void binary_cross_entropy_grad_custom(GM_ADDR logits, GM_ADDR labels, GM_ADDR grad, GM_ADDR weight, GM_ADDR outgrad)
{
    KernelBinaryCrossEntropyGrad op;
    op.Init(logits, labels, grad, weight, outgrad);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void binary_cross_entropy_grad_custom_do(uint32_t blockDim, void *stream, uint8_t *logits, uint8_t *labels,uint8_t *grad, uint8_t *weight, uint8_t *outgrad)
{
    binary_cross_entropy_grad_custom<<<blockDim, nullptr, stream>>>(logits, labels, grad, weight, outgrad);
}
#endif
